package com.morpheus.sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.location.Location;
import android.widget.Toast;

public class Geocoder 
{
	public static String reverseGeocode(Location loc)
	{		
	    	String Address="";
            StringBuffer sb=new StringBuffer();
	    	
	    	// build the URL using the latitude & longitude you want to lookup
            sb.append("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ Double.toString(loc.getLatitude()) + "," + Double.toString(loc.getLongitude()) +"&sensor=false");
            
            String url=sb.toString();
            HttpClient httpClient=new DefaultHttpClient();
            
            String responseData="";
            try {
                HttpResponse response=httpClient.execute(new HttpGet(url));
                response.addHeader("Accept-Language", "en-US");
                HttpEntity entity=response.getEntity();

                BufferedReader bf=new BufferedReader(new InputStreamReader((entity.getContent()),"UTF-8"));
                String line="";

                while((line=bf.readLine())!=null){
                    responseData=responseData+line;
                }

                JSONObject jsonObj = new JSONObject(responseData);

                JSONArray resultArry = jsonObj.getJSONArray("results");

                Address =resultArry.getJSONObject(0).getString("formatted_address").toString();
		    
			}
			catch (Exception ex)
			{
				Toast.makeText(null, ex.toString(), Toast.LENGTH_LONG).show();
			}
            return Address;
        }
}
			
	    
